package com.jboltai.event.chain;

import com.jboltai.config.JBoltAIConfig;
import com.jboltai.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventChainNode extends ChainNode<EventChainNode>{
    private static final Logger LOGGER = LoggerFactory.getLogger(JBoltAIConfig.LOGGER_NAME);


    private EventSupplier eventSupplier;

    private Event event;

    public EventChainNode(EventSupplier eventSupplier) {
        this.eventSupplier = eventSupplier;
    }

    public EventChainNode(String id, EventSupplier eventSupplier) {
        this.eventSupplier = eventSupplier;
        this.id = id;
    }

    @Override
    protected void execute() {


        try {

            this.event = this.eventSupplier.supply(chain);
            this.event.setChainNode(this);
            if (chain.mode == Chain.MODE_PUBLISH) {
                event.publish();
            } else {
                event.dispatch();
            }

        } catch (Exception e) {
            LOGGER.error("EventChainNode类型节点执行过程中发生异常", e);
            this.fail(e.getMessage(), e);

        }
    }

    public EventSupplier getEventSupplier() {
        return eventSupplier;
    }

    @Override
    protected void cancel() {
        this.event.cancel();
    }
}
